"use client"

import { StyleSheet, View, Alert, Platform } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { useRouter } from "expo-router"
import { theme } from "../constants/theme"
import { LinearGradient } from "expo-linear-gradient"
import { useState, useRef, useEffect } from "react"
import { CollectionModal } from "../components/learning/CollectionModal"
import { WordNavigation } from "../components/unit/WordNavigation"
import { WordCardContent } from "../components/unit/WordCardContent"
import { BottomNavigation } from "../components/unit/BottomNavigation"
import Animated, { useSharedValue, useAnimatedStyle, withTiming, Easing, runOnJS } from "react-native-reanimated"
import { UnitSettingsModal } from "../components/unit/UnitSettingsModal"
import AsyncStorage from "@react-native-async-storage/async-storage"

const WORDS_DATA = [
    {
        id: "1",
        word: "formulation",
        phonetic: "[ˌfɔːrmjuˈleɪʃ(ə)n]",
        type: "n.",
        meanings: ["公式化；阐述方式", "规划；配方"],
        syllables: ["for", "mu", "la", "tion"],
        phoneticSyllables: ["/f/", "/ɔː/", "/r/", "/m/", "/ju/", "/l/", "/eɪ/", "/ʃ/", "/ə/", "/n/"],
        examples: [
            {
                en: "He chose a milder formulation.",
                cn: "他选择了一种更温和的表述方式。",
            },
        ],
        status: "new", // new, learning, mastered
        favorite: false,
        etymology: {
            parts: [
                { text: "form", meaning: "形式" },
                { text: "ulate", meaning: "使...化" },
                { text: "ion", meaning: "名词后缀" },
            ],
            explanation: "form(形式) + ulate(使...化) + ion(名词后缀) = 公式化",
        },
        naturalReadingData: [
            { letter: "f", phonetic: "/f/", color: "#4B7FE5" },
            { letter: "o", phonetic: "/ɔː/", color: "#FF6B6B" },
            { letter: "r", phonetic: "/r/", color: "#4B7FE5" },
            { letter: "m", phonetic: "/m/", color: "#4B7FE5" },
            { letter: "u", phonetic: "/ju/", color: "#FF6B6B" },
            { letter: "l", phonetic: "/l/", color: "#4B7FE5" },
            { letter: "a", phonetic: "/eɪ/", color: "#FF6B6B" },
            { letter: "t", phonetic: "/t/", color: "#4B7FE5" },
            { letter: "i", phonetic: "/ɪ/", color: "#FF6B6B" },
            { letter: "o", phonetic: "/ə/", color: "#FF6B6B" },
            { letter: "n", phonetic: "/n/", color: "#4B7FE5" },
        ],
    },
    {
        id: "2",
        word: "favoritism",
        phonetic: "[ˈfeɪvərɪtɪzəm]",
        type: "n.",
        meanings: ["偏爱；偏袒；徇私"],
        syllables: ["fa", "vor", "i", "tism"],
        phoneticSyllables: ["/f/", "/eɪ/", "/v/", "/ə/", "/r/", "/ɪ/", "/t/", "/ɪ/", "/z/", "/ə/", "/m/"],
        examples: [
            {
                en: "The teacher was accused of favoritism.",
                cn: "这位老师被指责有偏袒行为。",
            },
        ],
        status: "learning",
        favorite: true,
        etymology: {
            parts: [
                { text: "favor", meaning: "偏爱" },
                { text: "ite", meaning: "...的" },
                { text: "ism", meaning: "主义；行为" },
            ],
            explanation: "favor(偏爱) + ite(...的) + ism(行为) = 偏袒行为",
        },
        naturalReadingData: [
            { letter: "f", phonetic: "/f/", color: "#4B7FE5" },
            { letter: "a", phonetic: "/eɪ/", color: "#FF6B6B" },
            { letter: "v", phonetic: "/v/", color: "#4B7FE5" },
            { letter: "o", phonetic: "/ə/", color: "#FF6B6B" },
            { letter: "r", phonetic: "/r/", color: "#4B7FE5" },
            { letter: "i", phonetic: "/ɪ/", color: "#FF6B6B" },
            { letter: "t", phonetic: "/t/", color: "#4B7FE5" },
            { letter: "i", phonetic: "/ɪ/", color: "#FF6B6B" },
            { letter: "s", phonetic: "/z/", color: "#4B7FE5" },
            { letter: "m", phonetic: "/əm/", color: "#4B7FE5" },
        ],
    },
    {
        id: "3",
        word: "turbine",
        phonetic: "[ˈtɜːbaɪn]",
        type: "n.",
        meanings: ["涡轮", "涡轮机"],
        syllables: ["tur", "bine"],
        phoneticSyllables: ["/t/", "/ɜː/", "/b/", "/aɪ/", "/n/"],
        examples: [
            {
                en: "Wind turbines generate electricity.",
                cn: "风力涡轮机发电。",
            },
        ],
        status: "new",
        favorite: false,
        naturalReadingData: [
            { letter: "t", phonetic: "/t/", color: "#5B8EF4" },
            { letter: "ur", phonetic: "/ɜː/", color: "#FF9500" },
            { letter: "b", phonetic: "/b/", color: "#5B8EF4" },
            { letter: "ine", phonetic: "/aɪn/", color: "#34C759" },
        ],
    },
    {
        id: "4",
        word: "supplementary",
        phonetic: "[ˌsʌplɪˈmentəri]",
        type: "adj./n.",
        meanings: ["补充性的；增补性的", "增补物"],
        syllables: ["sup", "ple", "men", "ta", "ry"],
        phoneticSyllables: ["/s/", "/ʌ/", "/p/", "/l/", "/ɪ/", "/m/", "/e/", "/n/", "/t/", "/ə/", "/r/", "/i/"],
        examples: [
            {
                en: "The teacher provided supplementary materials.",
                cn: "老师提供了补充材料。",
            },
        ],
        status: "new",
        favorite: false,
        naturalReadingData: [
            { letter: "s", phonetic: "/s/", color: "#5B8EF4" },
            { letter: "up", phonetic: "/ʌp/", color: "#FF9500" },
            { letter: "p", phonetic: "/p/", color: "#5B8EF4" },
            { letter: "l", phonetic: "/l/", color: "#34C759" },
            { letter: "i", phonetic: "/ɪ/", color: "#FF9500" },
            { letter: "men", phonetic: "/mɛn/", color: "#5B8EF4" },
            { letter: "t", phonetic: "/t/", color: "#34C759" },
            { letter: "a", phonetic: "/ə/", color: "#FF9500" },
            { letter: "ry", phonetic: "/ri/", color: "#5B8EF4" },
        ],
    },
    {
        id: "5",
        word: "abandon",
        phonetic: "[əˈbændən]",
        type: "v.",
        meanings: ["抛弃；放弃；中止"],
        syllables: ["a", "ban", "don"],
        phoneticSyllables: ["/ə/", "/b/", "/æ/", "/n/", "/d/", "/ə/", "/n/"],
        examples: [
            {
                en: "They had to abandon the sinking ship.",
                cn: "他们不得不放弃这艘下沉的船。",
            },
            {
                en: "Don't abandon hope.",
                cn: "不要放弃希望。",
            },
        ],
        status: "new",
        favorite: false,
        naturalReadingData: [
            { letter: "a", phonetic: "/ə/", color: "#FF6B6B" },
            { letter: "b", phonetic: "/b/", color: "#4B7FE5" },
            { letter: "a", phonetic: "/æ/", color: "#FF6B6B" },
            { letter: "n", phonetic: "/n/", color: "#4B7FE5" },
            { letter: "d", phonetic: "/d/", color: "#4B7FE5" },
            { letter: "o", phonetic: "/ə/", color: "#FF6B6B" },
            { letter: "n", phonetic: "/n/", color: "#4B7FE5" },
        ],
    },
]

export default function UnitLearningScreen() {
    const router = useRouter()
    const [isPlaying, setIsPlaying] = useState(false)
    const [isSlowPlaying, setIsSlowPlaying] = useState(false)
    const [isRecording, setIsRecording] = useState(false)
    const [currentWordIndex, setCurrentWordIndex] = useState(0)
    const [currentWord, setCurrentWord] = useState({
        ...WORDS_DATA[0],
        syllables: WORDS_DATA[0].syllables || [],
        meanings: WORDS_DATA[0].meanings || [],
        phoneticSyllables: WORDS_DATA[0].phoneticSyllables || [],
        examples: WORDS_DATA[0].examples || [],
        etymology: WORDS_DATA[0].etymology || {},
        naturalReadingData: WORDS_DATA[0].naturalReadingData || [],
    })
    const [collectionModalVisible, setCollectionModalVisible] = useState(false)
    const scrollViewRef = useRef(null)

    // 动画相关状态
    const cardOpacity = useSharedValue(1)
    const cardScale = useSharedValue(1)
    const cardTranslateX = useSharedValue(0)
    const [isAnimating, setIsAnimating] = useState(false)
    const [nextWordIndex, setNextWordIndex] = useState(null)

    const animatedCardStyle = useAnimatedStyle(() => {
        return {
            opacity: cardOpacity.value,
            transform: [{ scale: cardScale.value }, { translateX: cardTranslateX.value }],
        }
    })

    // 处理单词切换的动画
    const animateCardChange = (nextIndex) => {
        if (isAnimating) return

        setIsAnimating(true)
        setNextWordIndex(nextIndex)

        // 淡出并缩小当前卡片
        const direction = nextIndex > currentWordIndex ? -1 : 1

        cardOpacity.value = withTiming(0, { duration: 200, easing: Easing.out(Easing.ease) })
        cardScale.value = withTiming(0.9, { duration: 200, easing: Easing.out(Easing.ease) })
        cardTranslateX.value = withTiming(
            direction * 50,
            {
                duration: 200,
                easing: Easing.out(Easing.ease),
            },
            () => {
                runOnJS(completeAnimation)(nextIndex)
            },
        )
    }

    // 完成动画并更新单词
    const completeAnimation = (index) => {
        // 更新单词数据
        setCurrentWordIndex(index)
        setCurrentWord({
            ...WORDS_DATA[index],
            syllables: WORDS_DATA[index].syllables || [],
            meanings: WORDS_DATA[index].meanings || [],
            phoneticSyllables: WORDS_DATA[index].phoneticSyllables || [],
            examples: WORDS_DATA[index].examples || [],
            etymology: WORDS_DATA[index].etymology || {},
            naturalReadingData: WORDS_DATA[index].naturalReadingData || [],
        })

        // 重置动画值并淡入新卡片
        cardTranslateX.value = -50 * (index > currentWordIndex ? -1 : 1)

        // 淡入新卡片
        setTimeout(() => {
            cardOpacity.value = withTiming(1, { duration: 300, easing: Easing.out(Easing.ease) })
            cardScale.value = withTiming(1, { duration: 300, easing: Easing.out(Easing.ease) })
            cardTranslateX.value = withTiming(
                0,
                {
                    duration: 300,
                    easing: Easing.out(Easing.ease),
                },
                () => {
                    runOnJS(setIsAnimating)(false)
                },
            )
        }, 50)

        // 滚动头部导航到当前单词位置
        if (scrollViewRef.current) {
            scrollViewRef.current.scrollTo({
                x: index * 100, // 估计每个单词项的宽度
                animated: true,
            })
        }
    }

    const handleBack = () => {
        router.back()
    }

    const handlePlayAudio = (slow = false) => {
        if (slow) {
            setIsSlowPlaying(true)
            setTimeout(() => setIsSlowPlaying(false), 2000)
        } else {
            setIsPlaying(true)
            setTimeout(() => setIsPlaying(false), 2000)
        }
    }

    const handleRecord = () => {
        setIsRecording(!isRecording)
    }

    const handleWordChange = (index) => {
        if (index >= 0 && index < WORDS_DATA.length && index !== currentWordIndex) {
            animateCardChange(index)
        }
    }

    const handlePrevWord = () => {
        if (currentWordIndex > 0) {
            handleWordChange(currentWordIndex - 1)
        } else {
            Alert.alert("提示", "已经是第一个单词了")
        }
    }

    const handleNextWord = () => {
        if (currentWordIndex < WORDS_DATA.length - 1) {
            handleWordChange(currentWordIndex + 1)
        } else {
            Alert.alert("提示", "已经是最后一个单词了")
        }
    }

    const handleToggleFavorite = () => {
        // 如果已收藏，直接取消收藏
        if (currentWord.favorite) {
            const updatedWords = [...WORDS_DATA]
            updatedWords[currentWordIndex] = {
                ...updatedWords[currentWordIndex],
                favorite: false,
            }
            WORDS_DATA[currentWordIndex] = updatedWords[currentWordIndex]
            setCurrentWord({ ...updatedWords[currentWordIndex] })
        } else {
            // 如果未收藏，显示收藏弹窗
            setCollectionModalVisible(true)
        }
    }

    const handleUpdateStatus = (status) => {
        const updatedWords = [...WORDS_DATA]
        updatedWords[currentWordIndex] = {
            ...updatedWords[currentWordIndex],
            status: status,
        }
        WORDS_DATA[currentWordIndex] = updatedWords[currentWordIndex]
        setCurrentWord({ ...updatedWords[currentWordIndex] })
    }

    const handleConfirmCollection = (unitId, bookId) => {
        console.log(`收藏到: 课本ID=${bookId}, 单元ID=${unitId}`)

        // 更新收藏状态
        const updatedWords = [...WORDS_DATA]
        updatedWords[currentWordIndex] = {
            ...updatedWords[currentWordIndex],
            favorite: true,
        }
        WORDS_DATA[currentWordIndex] = updatedWords[currentWordIndex]
        setCurrentWord({ ...updatedWords[currentWordIndex] })

        setCollectionModalVisible(false)
    }

    const handleSettingsPress = () => {
        // 设置按钮的处理逻辑
        console.log("Settings pressed")
    }

    const [settingsModalVisible, setSettingsModalVisible] = useState(false)
    const [settings, setSettings] = useState({
        translationFontSize: 14,
        moduleFontSize: 12,
    })

    // Load settings from storage
    useEffect(() => {
        const loadSettings = async () => {
            try {
                const savedSettings = await AsyncStorage.getItem("unitLearningSettings")
                if (savedSettings) {
                    setSettings(JSON.parse(savedSettings))
                }
            } catch (error) {
                console.error("Failed to load settings:", error)
            }
        }
        loadSettings()
    }, [])

    const handleSettingsChange = async (newSettings: {
        translationFontSize?: number
        moduleFontSize?: number
    }) => {
        const updatedSettings = { ...settings, ...newSettings }
        setSettings(updatedSettings)
        try {
            await AsyncStorage.setItem("unitLearningSettings", JSON.stringify(updatedSettings))
        } catch (error) {
            console.error("Failed to save settings:", error)
        }
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                {/* 头部导航 */}
                <WordNavigation
                    ref={scrollViewRef}
                    words={WORDS_DATA}
                    currentIndex={currentWordIndex}
                    onWordSelect={handleWordChange}
                    onBackPress={handleBack}
                    onSettingsPress={() => setSettingsModalVisible(true)}
                />

                {/* 主要内容区域 - 固定高度的卡片 */}
                <View style={styles.contentContainer}>
                    <Animated.View style={[styles.animatedCardContainer, animatedCardStyle]}>
                        <WordCardContent
                            word={currentWord}
                            settings={settings}
                            isPlaying={isPlaying}
                            isSlowPlaying={isSlowPlaying}
                            isRecording={isRecording}
                            onPlayAudio={handlePlayAudio}
                            onRecord={handleRecord}
                            onUpdateStatus={handleUpdateStatus}
                            onToggleFavorite={handleToggleFavorite}
                        />
                    </Animated.View>
                </View>

                {/* 底部导航 */}
                <View style={styles.bottomNavContainer}>
                    <BottomNavigation
                        currentIndex={currentWordIndex}
                        totalCount={WORDS_DATA.length}
                        onPrevPress={handlePrevWord}
                        onNextPress={handleNextWord}
                    />
                </View>

                {/* 收藏弹窗 */}
                <CollectionModal
                    visible={collectionModalVisible}
                    onClose={() => setCollectionModalVisible(false)}
                    onConfirm={handleConfirmCollection}
                />
                <UnitSettingsModal
                    visible={settingsModalVisible}
                    onClose={() => setSettingsModalVisible(false)}
                    settings={settings}
                    onSettingsChange={handleSettingsChange}
                />
            </LinearGradient>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    contentContainer: {
        flex: 1,
        marginBottom: Platform.OS === "ios" ? 80 : 70, // 减小底部外边距
    },
    animatedCardContainer: {
        flex: 1,
    },
    bottomNavContainer: {
        position: "absolute",
        bottom: 0,
        left: 0,
        right: 0,
    },
})

